local julian = fk.CreateSkill {
  name = "julian$",
}

julian:addEffect(fk.AfterCardsMove, {
  anim_type = "drawcard",
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      return table.find(player.room.alive_players, function(p)
        return p ~= player and p.kingdom == "qun" and not p:isKongcheng()
      end)
    end
  end,
  on_trigger = function(self, event, target, player, data)
    for _, move in ipairs(data) do
      if move.to and move.to ~= player then
        local to = move.to
        if to and to.kingdom == "qun" and move.moveReason == fk.ReasonDraw and move.skillName ~= self.name 
          and to.phase ~= Player.Draw and to:getMark("julian-turn") < 2 and not to.dead then
          self:doCost(event, target, player, { to = to })
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if room:askForSkillInvoke(data.to, self.name, nil, "#julian-draw") then
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:addPlayerMark(data.to, "julian-turn", 1)
    data.to:drawCards(1, self.name)
  end,
})
julian:addEffect(fk.EventPhaseStart, {
  anim_type = "drawcard",
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      return table.find(player.room.alive_players, function(p)
        return p ~= player and p.kingdom == "qun" and not p:isKongcheng()
      end) and player.phase == Player.Finish
    end
  end,
  on_trigger = function(self, event, target, player, data)
    self:doCost(event, target, player, data)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if room:askForSkillInvoke(player, self.name, nil, "#julian-invoke") then
      event:setCostData(self,{
        tos = table.map(table.filter(room:getAlivePlayers(), function(p)
          return p ~= player and p.kingdom == "qun"
        end), Util.IdMapper)
      })
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local tos = table.map(event:getCostData(self).tos, Util.Id2PlayerMapper)
    for _, p in ipairs(tos) do
      if not p:isKongcheng() then
        local id = room:askForCardChosen(player, p, "h", self.name)
        room:obtainCard(player, id, false, fk.ReasonPrey, player.id, self.name)
        if player.dead then break end
      end
    end
  end,
})
return julian
